import axios from "axios";
import {notification} from 'antd';
import hash from 'hash.js';
import {getToken, storageClear,getUserInfo} from "./authority";
import {base_url} from "../config/const";
import {history} from '@/utils/utils';
import report from './errorReport'


const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};


axios.defaults.baseURL = base_url;
axios.defaults.timeout = 20000;

const service = axios;

service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = 'Bearer ' + getToken();
    return config;
  },
  error => {
    console.log('err: ' + error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => ({
    data: response.data,
    status: response.statusText,
    statusCode: response.status,
  }),
  error => {
    console.log('err: ' + error);
    if (error.message === "Network Error") {
      const rsp = error.response || {};
      const error_text = codeMessage[rsp.status] || '无法连接网络';
      notification.error({
        message: `错误请求 ${rsp.status || ''}`,
        description: error_text,
        duration: 5,
      });
      // return {};
    } else {
      const response = error.response;
      if (response.status === 401) {
        storageClear();
        if (response.data.detail === 'Invalid signature.') {
          notification.info({
            message: `信息更新需重新登录`,
            description: '3秒后跳转至登录页面',
            duration: 3,
          });

        } else {
          notification.error({
            message: `用户权限过期`,
            description: '3秒后跳转至登录页面',
            duration: 3,
          });
        }
        setTimeout(() => {
          // history.push({
          //   pathname: '/user/login',
          // });
          window.location.replace('/user/login')
        }, 3000)
      }else if(response.status >= 500){
        console.log(response);
        const url = response.request.responseURL;
        const msg = response.request.responseText;
        const reportMsg = {
          msg,
          url,
          row: 0,
          col: 0,
        }; // 错误信息
        report(reportMsg)
      }
      // return ({
      //   ...response.data || {},
      //   status: 'error',
      //   statusCode: response.status,
      // })
    }
    return Promise.reject(error)
  }
);

const cacheSave = (response, hashcode) => {
  const content = JSON.stringify(response);
  sessionStorage.setItem(hashcode, content);
  sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
  return response
};

const request = ({blacklist = [], whitelist = [], expiry = 60}) => async (config) => {
  const fingerprint = JSON.stringify(config);
  const isCache = whitelist.includes(config.url);
  const hashcode = hash.sha256().update(fingerprint).digest('hex');

  if (expiry !== 0) {
    const cached = sessionStorage.getItem(hashcode);
    const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
    if (cached !== null && whenCached !== null) {
      const age = (Date.now() - whenCached) / 1000;
      if (age < expiry) {
        return JSON.parse(cached);
      }
      sessionStorage.removeItem(hashcode);
      sessionStorage.removeItem(`${hashcode}:timestamp`)
    }
  }

  const rsp = await service(config);

  if (isCache) {
    cacheSave(rsp, hashcode)
  }
  return rsp

};

const ajax = request({whitelist: ['userstays/'], blacklist: [], expiry: 120});
export default ajax;
